{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import gzip, struct\n",
    "import numpy as np\n",
    "data_dir = '/home/sinyer/python/data/mnist'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def load_mnist():\n",
    "    def read_data(label_dir, image_dir):\n",
    "        with gzip.open(label_dir) as flbl:\n",
    "            struct.unpack(\">II\", flbl.read(8))\n",
    "            label = np.fromstring(flbl.read(), dtype=np.int8)\n",
    "        with gzip.open(image_dir, 'rb') as fimg:\n",
    "            _, _, rows, cols = struct.unpack(\">IIII\", fimg.read(16))\n",
    "            image = np.fromstring(fimg.read(), dtype=np.uint8).reshape(len(label), rows, cols)\n",
    "            image = image.reshape(image.shape[0], 1, 28, 28).astype(np.float32)/255\n",
    "        return label, image\n",
    "    train_label, train_img = read_data(\n",
    "        data_dir+'/train-labels-idx1-ubyte.gz', data_dir+'/train-images-idx3-ubyte.gz')\n",
    "    test_label, test_img = read_data(\n",
    "        data_dir+'/t10k-labels-idx1-ubyte.gz', data_dir+'/t10k-images-idx3-ubyte.gz')\n",
    "    return train_img, train_label, test_img, test_label\n",
    "\n",
    "def distance(train_data, test_data, i):\n",
    "    _list = []\n",
    "    dist = np.abs(train_data - test_data[i,:])\n",
    "    for j in range(len(dist)):\n",
    "        _list.append(np.sum(dist[j]))\n",
    "    return _list\n",
    "\n",
    "class knn:\n",
    "    def __init__(self):\n",
    "        pass\n",
    "    def train(self, train_data, train_label):\n",
    "        self.train_data = train_data\n",
    "        self.train_label = train_label\n",
    "    def predict(self, test_data):\n",
    "        test_num = test_data.shape[0]\n",
    "        pred_label = np.zeros(test_num)\n",
    "        for i in range(test_num):\n",
    "            index = np.argmin(distance(train_data, test_data, i))\n",
    "            pred_label[i] = self.train_label[index]\n",
    "        return pred_label"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_img, train_label, test_img, test_label = load_mnist()\n",
    "\n",
    "train_data = train_img[:5000].astype(np.float16)\n",
    "test_data = test_img[:100].astype(np.float16)\n",
    "train_label = train_label[:5000]\n",
    "test_label = test_label[:100]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.89\n"
     ]
    }
   ],
   "source": [
    "net = knn()\n",
    "net.train(train_data, train_label)\n",
    "test_pred = net.predict(test_data)\n",
    "acc = np.mean(test_pred == test_label)\n",
    "print(acc)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
